import { login, logout, getInfo, register, miniAppLogin } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getInfoByUserId } from "@/api/useradditionalinfo/info";
import defAva from "@/static/images/profile.jpg";
import { defineStore } from "pinia";
import { usePostStore } from './post'

export interface LoginForm {
	username : string;
	password : string;
	code : string;
	uuid : string;
}

const useUserStore = defineStore("user", {
	state: () => ({
		user: {},
		token: getToken(),
		name: "",
		avatar: "",
		nickName: "", // 添加 nickName 属性
		roles: Array(),
		permissions: [],
		userAdditionalInfo: {}
	}),
	getters: {
		// 获取用户ID
		userId: (state) => state.user.userId,
		// 获取当前积分
		currentPoints: (state) => state.userAdditionalInfo.currentPoints || 0
	},
	actions: {
		// 登录
		login(userInfo : LoginForm) {
			const username = userInfo.username.trim();
			const password = userInfo.password;
			const code = userInfo.code;
			const uuid = userInfo.uuid;
			return new Promise((resolve, reject) => {
				login(username, password, code, uuid)
					.then((res : any) => {
						setToken(res.token);
						this.token = res.token;
						resolve(null);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		miniAppLogin(phonenumber : string) {
			return new Promise((resolve, reject) => {
				miniAppLogin(phonenumber)
					.then((res : any) => {
						setToken(res.token);
						this.token = res.token;
						resolve(null);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 注册
		register(userInfo : LoginForm) {
			return new Promise((resolve, reject) => {
				register(userInfo)
					.then((res : any) => {
						resolve(res.msg);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 获取用户信息
		getInfo() {
			return new Promise((resolve, reject) => {
				getInfo()
					.then((res : any) => {
						const loginUser = res.user;
						const avatar =
							loginUser.avatar;
							console.log(avatar)

						if (res.roles && res.roles.length > 0) {
							// 验证返回的roles是否是一个非空数组
							this.roles = res.roles;
							this.permissions = res.permissions;
						} else {
							this.roles = ["ROLE_DEFAULT"];
						}
						this.name = loginUser.userName;
						this.nickName = loginUser.nickName; // 获取 nickName 并赋值
						this.avatar = avatar;
						this.user = loginUser

						// 获取用户额外信息
						getInfoByUserId(this.user.userId)
							.then((additionalRes : any) => {
								this.userAdditionalInfo = additionalRes.data || {};
								resolve(res);
							})
							.catch((additionalError) => {
								console.error('获取用户额外信息失败:', additionalError);
								// 即使获取额外信息失败，也不影响主要的用户信息获取
								this.userAdditionalInfo = {};
								resolve(res);
							});
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 退出系统
		logOut() {
			return new Promise<null>((resolve, reject) => {
				logout()
					.then(() => {
						this.token = "";
						this.roles = [];
						this.permissions = [];
						this.name = "";
						this.nickName = "";
						this.avatar = "";
						this.user = {};
						this.userAdditionalInfo = {};
						removeToken();
						resolve(null);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 在登出方法中添加
		logout() {
			return new Promise((resolve, reject) => {
				logout(this.token)
					.then(() => {
						this.token = ''
						this.roles = []
						this.permissions = []
						removeToken()

						// 清空帖子相关数据
						const postStore = usePostStore()
						postStore.clearUserLikedPosts()

						resolve(null)
					})
					.catch((error) => {
						reject(error)
					})
			})
		}
	},
});

export default useUserStore;